package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.NewShenHe;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private NewShenHe newShenHe;



    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1.非空判断
        dto.checkParam();
        //2.分页查询
        PageHelper.startPage(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper= Wrappers.lambdaQuery();
        //2.1 根据状态查询
        if(dto.getStatus()!=null){
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //2.2 根据关键字查询
        if(!StringUtils.isEmpty(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        //2.3 根据频道id查询
        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //2.4 根据开始和结束时间查询
        if(dto.getBeginPubdate()!=null && dto.getEndPubdate()!=null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }

        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        List<WmNews> wmNews = wmNewsMapper.selectList(queryWrapper);

        PageInfo<WmNews> pageInfo = new PageInfo<>(wmNews);
        Page page=new Page<>();
        page.setTotal(pageInfo.getTotal());
        page.setRecords(pageInfo.getList());
        ResponseResult result = new ResponseResult();
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 保存-修改-提交草稿为一体的方法
     *  主方法
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //TODO

        if (null==dto.getId()){
            if (dto.getStatus()==1){
                //提交审核文章
               if (TextLoad(dto)){
                   return ResponseResult.okResult("发布文章完成");
               }else {
                   return ResponseResult.errorResult(404,"文章内容不合法");
               }


            }
            else {
                if (TextLoad(dto)){
                    return ResponseResult.okResult("草稿完成");
                }else {
                    return ResponseResult.errorResult(404,"文章内容不合法");
                }

            }
        }else {

            wmNewsMapper.deleteById(dto.getId());
            LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId,dto.getId());
            wmNewsMaterialMapper.delete(lambdaQueryWrapper);
            if(dto.getStatus()==1){
                if (TextLoad(dto)){
                    return ResponseResult.okResult("发布文章完成");
                }else {
                    return ResponseResult.errorResult(404,"文章内容不合法");
                }
            }else {
                if (TextLoad(dto)){
                    return ResponseResult.okResult("草稿完成");
                }else {
                    return ResponseResult.errorResult(404,"文章内容不合法");
                }
            }


        }
    }













        //6.返回数据


    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
       //TODO
        LambdaUpdateWrapper<WmNews> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable());
        wmNewsMapper.update(new WmNews(), lambdaUpdateWrapper);
        WmNews wmNews = wmNewsMapper.selectById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(404,"文章不存在");
        }
        if (wmNews.getStatus()!=9){
            return ResponseResult.errorResult(404,"文章不是审核通过的状态");
        }
        rabbitTemplate.convertAndSend(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,"keyiu",wmNews);
        return ResponseResult.okResult("文章上下架完成");
    }

    @Override
    public ResponseResult delnews(Integer id) {
        wmNewsMapper.deleteById(id);
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getNewsId,id);
        wmNewsMaterialMapper.delete(lambdaQueryWrapper);
        return ResponseResult.okResult("删除文章完成");
    }



    public Boolean TextLoad(WmNewsDto dto){


        WmNews wmNews = BeanUtil.toBean(dto, WmNews.class);
        WmUser user = WmThreadLocalUtil.getUser();
        wmNews.setUserId(user.getId());
        wmNews.setCreatedTime(new Date());
        String images1 = wmNews.getImages();
        String s = images1.replaceAll("\\[", "");
        String s1 = s.replaceAll("\\]", "");
        wmNews.setImages(s1);
        Wmaparticle apArticle = BeanUtil.toBean(wmNews, Wmaparticle.class);
        apArticle.setAuthorId(user.getId());
        apArticle.setAuthorName(user.getName());

        rabbitTemplate.convertAndSend(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,
                WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_ROUTINGKEY,apArticle);

        wmNewsMapper.insert(wmNews);
        Boolean b = newShenHe.shenHe(wmNews);

        WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
        List<String> images = dto.getImages();
        wmNewsMaterial.setNewsId(wmNews.getId());
        for (String image : images) {
            LambdaQueryWrapper<WmMaterial> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.eq(WmMaterial::getUrl, image);
            List<WmMaterial> wmMaterial =  wmMaterialMapper.selectList(queryWrapper1);
            for (WmMaterial material : wmMaterial) {
                wmNewsMaterial.setType((short) 1);
                wmNewsMaterial.setMaterialId(material.getId());
                wmNewsMaterialMapper.insert(wmNewsMaterial);
            }
        }
        String content = wmNews.getContent();
        JSONArray objects = JSON.parseArray(content);
        for (Object object : objects) {
            JSONObject jsonObject= (JSONObject) object;
            if (jsonObject.get("type").equals("image")){
                String url = jsonObject.getString("value");
                LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.lambdaQuery();
                queryWrapper.eq(WmMaterial::getUrl, url);
                List<WmMaterial> wmMaterial =  wmMaterialMapper.selectList(queryWrapper);
                for (WmMaterial material : wmMaterial) {
                    wmNewsMaterial.setType((short) 0);
                    wmNewsMaterial.setMaterialId(material.getId());
                    wmNewsMaterialMapper.insert(wmNewsMaterial);
                }
            }
        }
        return b;
    }



        }


